<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="${request.contextPath}/statics/css/wsDangan.css">
    <link rel="stylesheet" href="${request.contextPath}/statics/css/bootstrap.css">

    <!-- 引入组件库 -->
    <script src="${request.contextPath}/statics/libs/jquery.min.js"></script>
    <script src="${request.contextPath}/statics/vue/vue.js"></script>
    <script src="${request.contextPath}/statics/vue/index.js"></script>
    <script src="${request.contextPath}/statics/vue/axios.js"></script>
    <link rel="stylesheet" href="${request.contextPath}/statics/vue/index.css">
    <script src="${request.contextPath}/statics/js/config.js"></script>
    <script src="${request.contextPath}/statics/js/bootstrap.js"></script>

    <title>用户管理</title>
</head>
<body class="body" style="background-color:#fff">
<div id="app" class="container app" style="width: 100%;height: 100%;padding:0px;">
    <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="用户管理" name="user">
            <el-container>
                <el-aside width="300px">
                    <el-input
                            placeholder="输入关键字进行过滤"
                            :model="deptFilterName">
                    </el-input>
                    <el-tree :data="deptData" :props="defaultProps"
                             lazy
                             highlight-current="true"
                             empty-text="部门加载中"
                             @node-click="deptNodeClick"
                             style="width: 100%;max-height: 660px;"
                             :expand-on-click-node="false"
                             element-loading-text="正在删除知识点中的此标签..."
                             element-loading-spinner="el-icon-loading"
                             :load="loadDept"></el-tree>
                </el-aside>
                <el-main style="padding: 0px 20px">
                    <el-form :inline="true" :model="addUserForm" ref="addUserForm" :rules="addUserForm.rules"
                             class="demo-form-inline">
                        <el-form-item label="用户名：" prop="username">
                            <el-input v-model="addUserForm.username" placeholder="输入用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="密码：">
                            <el-input v-model="addUserForm.password" ></el-input>
                        </el-form-item>
                        <el-form-item label="手机号：">
                            <el-input v-model="addUserForm.mobile" ></el-input>
                        </el-form-item>
                        <el-form-item label="部门：">
                            <el-input v-model="addUserForm.deptName" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="addUser">添加</el-button>
                        </el-form-item>
                    </el-form>
                    <el-pagination
                            style="margin-bottom: 10px;"
                            background
                            layout="prev,pager, next,total"
                            @current-change="userPageChange"
                            @prev-click="userPageChange"
                            @next-click="userPageChange"
                            :current-page="page.currPage"
                            :total="page.totalCount">
                    </el-pagination>
                    <el-table
                            :data="userTableData"
                            stripe
                            border
                            header-align="center"
                            align="center"
                            size="mini"
                            height="600"
                            style="width: 100%;height: 600px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
                    >

                        <el-table-column
                                type="index"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="username"
                                label="用户名"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                label="用户名">
                            <template slot-scope="scope">
                                <el-tag
                                        :key="role.roleName"
                                        v-for="(role,index) in scope.row.roles"
                                        size="small"
                                        closable
                                        :disable-transitions="false"
                                        @close="deleteRole(scope.row,scope.$index,index)">
                                    {{role.roleName}}
                                </el-tag>
                                <el-button icon="el-icon-plus" size="mini"
                                           @click="handleAddRole(scope.row,scope.$index)" type="primary" plain>添加
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column

                                label="查询档案类别">
                            <template slot-scope="scope">
                                <el-checkbox-group v-model="scope.row.flhs">
                                    <el-checkbox v-for="flh in optionsData.flhOptions" :label="flh.value">{{flh.value}}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </template>
                        </el-table-column>
                        <el-table-column

                                label="所在地">
                            <template slot-scope="scope">
                                <el-checkbox-group v-model="scope.row.szds">
                                    <el-checkbox v-for="szd in optionsData.szdOptions" :label="szd.value"
                                                 :key="szd.value">
                                        {{szd.value}}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" @click="updateUser(scope.row)" size="mini">保存</el-button>
                                <el-button type="default" @click="resetPassword(scope.row)" size="mini">重置密码</el-button>
                                <el-button type="danger" @click="deleteUser(scope.row)" size="mini">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-main>
            </el-container>
        </el-tab-pane>
    </el-tabs>

    <el-dialog
            :visible.sync="roleDialogVisible"
            center
            modal=false>
        <el-select v-model="selectRole" value-key="roleId" placeholder="请选择">
            <el-option
                    v-for="item in roleDate"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item">
            </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
            <el-button  @click="roleDialogVisible=false,selectRole=''">取  消</el-button>
            <el-button type="primary" @click="addUserRole">添  加</el-button>
          </span>
    </el-dialog>

</div>


</body>
<script type="text/javascript">
    const http = axios.create({

        baseURL: getUrl(),
        timeout: 100000,
        withCredentials: false, // 是否允许带cookie这些
        // headers: {'Content-Type': 'application/json'}
    });
    var vm = new Vue({
        el: '#app',
        data: {
            deptFilterName: '',
            defaultProps: {
                children: 'subDeptList',
                label: 'name'
            },
            deptSelected: {},//tree中选中的部门
            deptData: [],//部门数据
            szdT: ['江北', "鄞州"],
            flhT: ['A', 'B'],
            userTableData: [],//用户数据
            page: {
                totalCount: 0,
                pageSize: 10,
                totalPage: 1,
                currPage: 1,
            },
            optionsData: {
                szdOptions: [],
                flhOptions: [],
            },
            addUserForm: {
                username: '',
                password: 'abcd1234',
                deptId: 0,
                deptName: '',
                rules: {
                    username: [{required: true, message: '请输入登录名', trigger: 'blur'}]
                },
                cardNo:'',
                mobile:'',
            },
            selectDeptId: 0,
            activeTab: 'user',
            roleDialogVisible: false,
            roleDate: [],
            selectRole: '',
            roleAddUserIndex:0,
        },
        mounted() {
            this.loadFlhOptions()
            this.loadSzdOptions()
            this.loadTopDept()
        },
        methods: {
            deleteRole(role, userIndex,roleIndex) {
                console.info("刪除角色" + role);
                this.userTableData[userIndex].roles.splice(roleIndex,1)
                let roleIdIndex=this.userTableData[userIndex].roleIds.indexOf(role.roleId)
                this.userTableData[userIndex].roleIds.splice(roleIdIndex,1)

                console.info("删除后roleIds："+this.userTableData[userIndex].roleIds.length)
                console.info("删除后roles："+this.userTableData[userIndex].roles.length)
            },
            deptNodeClick(dept) {
                this.addUserForm.deptName = dept.name
                this.addUserForm.deptId = dept.deptId
                this.loadUser()
            },
            userPageChange(page) {//翻页
                this.page.currPage = page
                this.loadUser()
            },
            loadUser() {
                let params = new URLSearchParams()
                params.append("deptId", this.addUserForm.deptId)
                params.append("page", this.page.currPage)
                http.post('/sys/user/listDetail', params).then(function (resp) {
                    console.log(resp)
                    this.userTableData = resp.data.page.list
                    this.page.totalCount = resp.data.page.total
                    this.page.pageSize = resp.data.page.pageSize
                    this.page.totalPage = resp.data.page.pages
                    this.page.currPage = resp.data.page.pageNum
                }.bind(this)).catch(function (err) {
                    console.error(err)
                })

            },
            addUser() {
                this.$confirm('是否添加该用户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = new URLSearchParams()
                    http.post('/sys/user/save', JSON.stringify({
                            username: this.addUserForm.username, deptId: this.addUserForm.deptId
                            , password: this.addUserForm.password, status: 1,mobile:this.addUserForm.mobile,
                            hasResetPwd:0
                        }),
                        {
                            headers: {'Content-Type': 'application/json'}
                        }
                    ).then(function (resp) {
                        console.log(resp.data)
                        if (resp.data.code == 0) {
                            this.$message.success("添加用户成功")
                        } else {
                            this.$message.error("添加用户失败")
                        }
                    }.bind(this)).catch(function (err) {
                        console.error(err)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消添加'
                    });
                });
            },
            deleteUser(user){
                this.$confirm('确认删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var userIds=new Array()
                    userIds.push(user.userId)
                    $.ajax({
                        type: "POST",
                        url: getUrl() + "/sys/user/delete",
                        contentType: "application/json",
                        data: JSON.stringify(userIds),
                        success: function(r){
                            if(r.code == 0){
                                alert('删除成功', function(){
                                    vm.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleAddRole(user, index) {
                this.roleAddUserIndex=index
                let params = new URLSearchParams();
                params.append("limit", 1000);
                http.post('/sys/role/list', params).then(function (resp) {
                    console.log(resp)
                    if (resp.data.code == 0) {
                        this.roleDialogVisible = true;
                        let roleList = new Array();
                        resp.data.page.list.forEach(function (role) {
                            if (!user.roleIds.includes(role.roleId)) {
                                roleList.push({
                                    roleId:role.roleId,
                                    roleName:role.roleName
                                })
                            }
                        });
                        this.roleDate = roleList;
                    }
                }.bind(this)).catch(function (err) {
                    console.error(err)
                    this.$message.error("保存用户区域失败")

                })
            },
            addUserRole() {
                console.info(this.selectRole)
                this.userTableData[this.roleAddUserIndex].roleIds.push(this.selectRole.roleId)
                this.userTableData[this.roleAddUserIndex].roles.push(this.selectRole)
                this.roleDialogVisible=false
            },
            updateUser(user) {
                // this.saveUserFlh(user)
                // this.saveUserSzd(user)
                let params = new URLSearchParams()
                params.append("userId", user.userId)
                params.append("locations", user.szds)
                params.append("flhs", user.flhs)
                params.append("roleIds", user.roleIds)
                http.post('/sys/user/saveUserRoleFlhSzd', params).then(function (resp) {
                    console.log(resp)
                    if (resp.data.code == 0) {
                        this.$message.success("保存用户区域成功")
                    } else {
                        this.$message.error("保存用户区域失败")
                    }
                }.bind(this)).catch(function (err) {
                    console.error(err)
                    this.$message.error("保存用户区域失败")
                })
            },
            saveUserSzd(user) {
                let params = new URLSearchParams()
                params.append("userId", user.userId)
                params.append("daUserLocationList", user.szds)
                http.post('/dangan/dauserlocation/updateBatch', params).then(function (resp) {
                    console.log(resp)
                    if (resp.data.code == 0) {
                        this.$message.success("保存用户区域成功")
                    } else {
                        this.$message.error("保存用户区域失败")
                    }
                }.bind(this)).catch(function (err) {
                    console.error(err)
                    this.$message.error("保存用户区域失败")

                })
            },
            saveUserFlh(user) {
                let params = new URLSearchParams()
                params.append("userId", user.userId)
                params.append("daUserFlh", user.flhs)
                http.post('/dangan/dauserflh/saveBatch', params).then(function (resp) {
                    console.log(resp)
                    if (resp.data.code == 0) {
                        this.$message.success("保存用户分类号成功")
                    } else {
                        this.$message.error("保存用户分类号失败")
                    }
                }.bind(this)).catch(function (err) {
                    console.error(err)
                    this.$message.error("保存用户分类号失败")

                })

            },
            resetPassword(user) {
                this.$confirm('是否重置该用户密码为abcd1234, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = new URLSearchParams()
                    params.append("newPassword", "abcd1234")
                    params.append("userId", user.userId)
                    http.post('/sys/user/resetPassword', params).then(function (resp) {
                        console.log(resp.data)
                        if (resp.data.code == 0) {
                            this.$message.success("重置密码成功")
                        } else {
                            this.$message.error("重置密码失败")
                        }
                    }.bind(this)).catch(function (err) {
                        console.error(err)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            /**
             * 加载顶级部门
             */
            loadTopDept() {
                http.post('/sys/dept/topDept').then(function (resp) {
                    console.log(resp.data)
                    this.deptData.push(resp.data)
                    this.addUserForm.deptName = resp.data.name
                    this.addUserForm.deptId = resp.data.deptId
                    this.loadUser()
                }.bind(this)).catch(function (err) {
                    console.error(err)
                })
            },
            loadDept(node, resolve) {
                if (node.id != 0) {
                    let params = new URLSearchParams()
                    params.append("parentId", node.data.deptId)
                    http.post('/sys/dept/find', params).then(function (resp) {
                        // console.log("子部门：" + resp.data)
                        if (resp.status == 200) {
                            let list = resp.data;
                            let subDeptList = [];
                            list.forEach(function (it) {
                                subDeptList.push(
                                    {
                                        name: it.name,
                                        deptId: it.deptId,
                                        isLeaf: false,
                                    }
                                )
                            });
                            return resolve(subDeptList)
                        } else {
                            return resolve([]);//没有子分类
                        }
                    }.bind(this)).catch(function (err) {
                        console.error(err)
                    })
                }
            },
            loadSzdOptions() {
                http.post('/sys/dict/list?type=' + "szd").then(function (resp) {
                    this.optionsData.szdOptions = resp.data.page.list
                    console.log(resp)
                }.bind(this)).catch(function (err) {
                    console.error(err)
                })
            },
            loadFlhOptions() {
                http.post('/sys/dict/list?type=' + "flh").then(function (resp) {
                    console.log(resp)
                    this.optionsData.flhOptions = resp.data.page.list
                }.bind(this)).catch(function (err) {
                    console.error(err)
                })
            }
        }
    })
</script>
</html>



